package com.hyt.it.ogt.ks.service.Event;

import com.hyt.it.ogt.ks.config.ConfigManager;
import com.hyt.it.ogt.opertaion.track.service.IOperationTrackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * 异步保存轨迹
 */
@Component
@Slf4j
public class LogListener implements ApplicationListener<LogEvent>, DisposableBean {
    // 5分钟间隔没有更新，就刷轨迹到数据库
    public static final long TIME = 5 * 60 * 1000;
    private final ConcurrentLinkedDeque<Object> answerLogQueue = new ConcurrentLinkedDeque<>();
    @Resource
    private ConfigManager configManager;
    private Date lastUpdateDate = new Date();
    @Resource
    private IOperationTrackService iOperationTrackService;

    @Override
    public void onApplicationEvent(LogEvent event) {
        /*if (event == null) {
            return;
        }
        log.debug(" # LogEvent开始消费轨迹: {}", JSON.toJSONString(event));
        if (event.getLogs() != null) {
            this.pushToQueue(event.getLogs());
            this.save(configManager.getLogEventCapacity());
        }
        if (event.getForceExec() != null
                && event.getForceExec()
                && System.currentTimeMillis() - this.getLastUpdateDate().getTime() >= TIME
                && answerLogQueue.size() > 0) {
            // 防止队列里面数据一直存放，通过xxlJob定时刷新入库，有一定延迟
            this.save(configManager.getLogEventCapacity());
        }
        if (event.getAnswerLogVO() != null) {
            this.pushToQueue(event.getAnswerLogVO());
            this.save(configManager.getLogEventCapacity());
        }
        if (event.getOtherLogVO() != null) {
            this.pushToQueue(event.getOtherLogVO());
            this.save(configManager.getLogEventCapacity());
        }
        log.debug(" # LogEvent结束消费轨迹");*/
    }

    /*private void pushToQueue(Object obj) {
        if (obj != null) {
            answerLogQueue.add(obj);
        }
    }

    */

    /**
     * 暂时不动
     *
     * @param data 数据
     *//*
    private void pushToQueue(List<CandidateLog> data) {
        data.parallelStream().forEach(item -> {
            AnswerLogVO log = AnswerLogVO.builder().examId(item.getExamId()).candidateId(item.getCandidateId())
                    .beginTime(DateUtil.date2String(item.getBeginTime())).eventType(item.getEventType())
                    .operateType(item.getOperateType()).itemId(item.getItemId())
                    .operateContent(JSON.toJSONString(AnswerVO.builder().answer(item.getOperateContent())))
                    .build();
            // 在此deque的尾部插入指定的元素
            answerLogQueue.add(log);
        });
        this.setLastUpdateDate(new Date());
    }

    private void save(int len) {
        List<OtherLogVO> otherLogList = new ArrayList<>();
        List<AnswerLogVO> answerLogList = new ArrayList<>();
        try {
            if (len <= answerLogQueue.size()) {
                for (int i = 0; i < len; i++) {
                    // 检索并删除由此deque表示的队列的第一个元素
                    Object one = answerLogQueue.pollFirst();
                    if (one == null) {
                        break;
                    } else {
                        if (one instanceof CandidateLogAnswer) {
                            answerLogList.add((AnswerLogVO) one);
                        } else if (one instanceof OtherLogVO) {
                            otherLogList.add((OtherLogVO) one);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("# 消费轨迹异常", e);
        } finally {
            try {
                if (answerLogList.size() > 0) {
                    iOperationTrackService.answerTrackLogSave(answerLogList);
                }
                if (otherLogList.size() > 0) {
                    iOperationTrackService.otherTrackLogSave(otherLogList);
                }
            } catch (Exception e) {
                log.error("# 保存轨迹异常", e);
            }
        }
    }*/
    @Override
    public void destroy() {
       /* if (answerLogQueue.size() > 0) {
            this.save(answerLogQueue.size());
        }*/
    }
/*
    public Date getLastUpdateDate() {
        return lastUpdateDate;
    }

    public void setLastUpdateDate(Date lastUpdateDate) {
        this.lastUpdateDate = lastUpdateDate;
    }*/
}
